package com.seuic.hnapps.device_implement;


import android.graphics.Bitmap;
import android.os.RemoteException;
import android.util.Log;

import com.seuic.android.PrintBitmapListener;
import com.seuic.hnapps.posdsdk.device_interface.PrinterDevice;


import java.io.ByteArrayOutputStream;

public class PrinterDeviceImp extends BaseImplement implements PrinterDevice {

    private static PrinterDeviceImp self;

    private PrinterDeviceImp() {
    }

    static PrinterDeviceImp getInstance() {
        if ( self == null ) {
            synchronized ( PrinterDeviceImp.class ) {
                if ( self == null ) {
                    self = new PrinterDeviceImp();
                }
            }
        }
        return self;
    }
    private  PrintCallback printCallback = null;

    @Override
    public void printBitmap(PrintCallback printCallback, Bitmap bitmap) {
        if ( printCallback == null ) {
            Log.e( LOG_TAG, "printCallback == null" );
            setLastError( "Input Param Error" );
            return;
        }
        this.printCallback = printCallback;
        if ( printer == null ) {
            Log.e( LOG_TAG, "printer == null" );
            PrinterCallbackOnFail( "Printer Service Error" );
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress( Bitmap.CompressFormat.JPEG, 100, stream );
        try {
            int result = printer.printBitmap( new PosdPrintBitmapListener(), stream.toByteArray() );
            if ( result == -2 ) {
                PrinterCallbackOnFail( "Battery Low" );
            } else if ( result < 0 ) {
                Log.e( LOG_TAG, "receipt.Print Failed: " + result );
                PrinterCallbackOnFail( "Printer Service Error" );
            }
        } catch (RemoteException e) {
            Log.e( LOG_TAG, "RemoteException: " + e );
            setLastError( "Printer Service Error RemoteException: " + e );
        }
    }

    private void PrinterCallbackOnFail(final String error ) {
        if ( printer == null ) {
            return;
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                printCallback.onFailed( error );
            }
        });
    }

    private class PosdPrintBitmapListener extends PrintBitmapListener.Stub {

        @Override
        public void OnSuccess() throws RemoteException {
            if ( printCallback == null ) {
                return;
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    printCallback.onSuccess();
                }
            });
        }

        @Override
        public void OnFail(int returnCode) throws RemoteException {
            if ( returnCode == -2 ) {
                PrinterCallbackOnFail( "Lack Paper" );
            } else {
                PrinterCallbackOnFail( "Print Failed: " + returnCode );
            }
        }
    }
}
